package com.ruoyi.module.file.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.module.file.utils.FileUtils;
import com.ruoyi.system.service.ISysDictDataService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author yqq
 * @date 2024/1/29
 * @Description
 */
@RestController
@RequestMapping("/api/file")
public class FileController {

    @Resource
    private ISysDictDataService sysDictDataService;

    /**
     * 文件上传
     */
    @Log(title = "文件上传", businessType = BusinessType.EXPORT)
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file)
    {
        String endpoint = getValue("endpoint");
        String keyId = getValue("keyId");
        String keySecret = getValue("keySecret");
        String bucketName = getValue("bucketName");
        try {
            return AjaxResult.success(FileUtils.upload(file,endpoint,keyId,keySecret,bucketName));
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }

    public String getValue(String str){
        String value="";
        List<SysDictData> sysDictData = sysDictDataService.selectDictDataList(new SysDictData());
        for (SysDictData sysDictDatum : sysDictData) {
            if (str.equals(sysDictDatum.getDictType())){
                value=sysDictDatum.getDictValue();
                break;
            }
        }
        if (StringUtils.isBlank(value)){
            throw new BaseException("oos-未配置，请先配置");
        }
        return value;
    }

}
